package com.dongdongshop.util;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;

import java.io.File;
import java.util.Date;

@Component
public class JavaMailUtils {

    @Resource
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String form;

    public void sendSimpleMail(String to,String subject,String text) {
        //构建邮件
        SimpleMailMessage msg = new SimpleMailMessage();
        //设置邮件主题
        msg.setSubject(subject);
        //设置邮件内容
        msg.setText(text);
        //邮件是谁发的，要写的和application.yml发邮件的用户名一致，不然发布出去
        msg.setFrom(form);
        //设置发邮件的时间
        msg.setSentDate(new Date());
        //接收方的qq邮箱
        msg.setTo(to);
        javaMailSender.send(msg);
    }
    public void sendFileEmail(String subject,String text,String form,String to,String fileName,String filePath) throws Exception{
        //通过JavaMailSender创建一个MimeMessage对象
        MimeMessage msg = javaMailSender.createMimeMessage();
        //传个true表示这个邮件的形式更加丰富,helper就是帮我们把邮件配置好
        MimeMessageHelper helper = new MimeMessageHelper(msg, true);
        helper.setSubject(subject);
        helper.setText(text);
        helper.setFrom(form);
        helper.setSentDate(new Date());
        helper.setTo(to);
        helper.addAttachment("aa.jpg",new File(filePath));
        javaMailSender.send(msg);
    }

}
